var numSquares = function(n) {
  if (n === 1) return 1;
  if (n === 2) return 2;

  const squareArr = getPerfectSquare(n);
  const dp = new Array(n + 1).fill(n);
  dp[0] = 0, dp[1] = 1, dp[2] = 2;

  for (let i = 0; i < squareArr.length; i++) {
    for (let j = squareArr[i]; j <= n; j++) {
      dp[j] = Math.min(dp[j], dp[j - squareArr[i]] + 1);
    }
  }
  return dp[n];

}

function getPerfectSquare(n) {
  let squareArr = [], i = 1;
  while (i * i <= n) {
    squareArr.push(i * i);
    i++;
  }
  return squareArr;
}

console.log(numSquares(12));